package cn.zs.supply.web.interceptor;

import cn.zs.supply.common.annotation.EscapeLogin;
import cn.zs.supply.common.core.login.domain.LoginInfo;
import com.sun.xml.internal.xsom.impl.Const;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@Component
public class ConfigPathInterceptor implements HandlerInterceptor {
    private static final String AUTHORIZATION_PREFIX = "Bearer ";

    private static final int AUTHORIZATION_PREFIX_LENGTH = AUTHORIZATION_PREFIX.length();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            EscapeLogin escapeLogin = handlerMethod.getMethodAnnotation(EscapeLogin.class);
            if (escapeLogin != null) {
                return true;
            }
        }
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization) || !authorization.startsWith(AUTHORIZATION_PREFIX)) {
            //handleFailure(response, ApiResponse.AUTHENTICATION_FAILURE);
            return false;
        }

        String token = authorization.substring(AUTHORIZATION_PREFIX_LENGTH);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}